package services

import (
	"context"
	"errors"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"

	"zwai-app/db"
	"zwai-app/models"
)

// CommentWithReplies 用于返回：一条评论 + 它的所有一级回复（平级扁平）
type CommentWithReplies struct {
	ID         string    `json:"id"`
	AuthorID   string    `json:"authorId"`
	AuthorName string    `json:"authorName"` // 新增
	Content    string    `json:"content"`
	CreatedAt  time.Time `json:"createdAt"`
	Replies    []Reply   `json:"replies,omitempty"`
}

// Reply 只包含一级回复信息
type Reply struct {
	ID         string    `json:"id"`
	AuthorID   string    `json:"authorId"`
	AuthorName string    `json:"authorName"` // 新增
	Content    string    `json:"content"`
	CreatedAt  time.Time `json:"createdAt"`
}

// GetCommentsFlat 返回两级评论列表：根评论 + 对应的所有一级回复，均带用户名
func GetCommentsFlat(ctx context.Context, articleIDStr string) ([]CommentWithReplies, error) {
	aid, err := primitive.ObjectIDFromHex(articleIDStr)
	if err != nil {
		return nil, errors.New("invalid article ID")
	}
	commentColl := db.Client.Database(db.DBName).Collection("Comment")
	userColl := db.Client.Database(db.DBName).Collection("User")

	// 1. 查出这篇文章的所有评论
	cursor, err := commentColl.Find(ctx, bson.M{"articleId": aid})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	// 临时缓存：所有根评论 & 二级回复表
	var roots []CommentWithReplies
	children := make(map[primitive.ObjectID][]models.Comment)

	for cursor.Next(ctx) {
		var c models.Comment
		if err := cursor.Decode(&c); err != nil {
			continue
		}
		if c.ParentID == nil {
			// 查用户名
			var u models.User
			if err := userColl.FindOne(ctx, bson.M{"_id": c.AuthorID}).Decode(&u); err != nil {
				u.Username = "未知用户"
			}

			roots = append(roots, CommentWithReplies{
				ID:         c.ID.Hex(),
				AuthorID:   c.AuthorID.Hex(),
				AuthorName: u.Username,
				Content:    c.Content,
				CreatedAt:  c.CreatedAt,
				Replies:    nil,
			})
		} else {
			// 一级回复，先缓存下来
			children[*c.ParentID] = append(children[*c.ParentID], c)
		}
	}

	// 2. 把一级回复挂到对应的根评论下
	for i, root := range roots {
		rid, _ := primitive.ObjectIDFromHex(root.ID)
		for _, c := range children[rid] {
			// 查回复者用户名
			var u models.User
			if err := userColl.FindOne(ctx, bson.M{"_id": c.AuthorID}).Decode(&u); err != nil {
				u.Username = "未知用户"
			}
			roots[i].Replies = append(roots[i].Replies, Reply{
				ID:         c.ID.Hex(),
				AuthorID:   c.AuthorID.Hex(),
				AuthorName: u.Username,
				Content:    c.Content,
				CreatedAt:  c.CreatedAt,
			})
		}
	}

	return roots, nil
}
